package com.banzhi.shop.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.banzhi.shop.R;
import com.banzhi.shop.adapter.GroupingPagerAdapter;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.data.GroupingIndexBean;
import com.banzhi.shop.data.GroupsadvBean;
import com.banzhi.shop.data.MessageEvent;
import com.banzhi.shop.data.MessageEvent2;
import com.banzhi.shop.fragment.GroupingSelectFragment;
import com.banzhi.shop.fragment.MyGroupingFragments;
import com.banzhi.shop.model.CallBack.GroupingCallBack;
import com.banzhi.shop.model.Impl.GroupingImpl;
import com.banzhi.shop.model.Impl.PinTuanImpl;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.LogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.TabLayoutUtil;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.banzhi.shop.view.FlyBanner;
import com.banzhi.shop.view.NoScrollViewPager;
import com.banzhi.shop.view.TitleBar;
import com.banzhi.shop.view.VpSwipeRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

//拼团(重构)
public class GroupActivity extends BaseActivity implements GroupingCallBack, SwipeRefreshLayout.OnRefreshListener {
    private TitleBar mTbGrouping;
    private FlyBanner mBanner;
    private TabLayout mTabs;
    public NoScrollViewPager mViewPager;
    private List<String> mTitle = new ArrayList<String>();
    private ArrayList<Fragment> mFragment = new ArrayList<Fragment>();
    private GroupingPagerAdapter mPagerAdapter;
    private AppBarLayout mAppBarLayout;
    private VpSwipeRefreshLayout mVpSwipeRefesh;
    // 必须通过new 对象进行初始化
    private List<String> networkImages = new ArrayList<>();
    private GroupingImpl mModel;
    private int page = 1;
    private GroupingIndexBean mDatabean;
    private List<GroupsadvBean> mGroupsadv ;
    private int position;
    private MainActivity mMainActivity;
    private ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_grouping2);
        Translucent.setTranslucent(this);
        initView();
        //注册
        EventBus.getDefault().register(this);
        mModel = new GroupingImpl();
        mModel.getData(page,20,GroupActivity.this);
        mPagerAdapter = new GroupingPagerAdapter(getSupportFragmentManager(), mTitle, mFragment);
        mViewPager.setAdapter(mPagerAdapter);
        //为TabLayout设置ViewPager
        mTabs.setupWithViewPager(mViewPager);
        //使用ViewPager的适配器
        mTabs.setTabsFromPagerAdapter(mPagerAdapter);
        //定义tablayout下划线的长度
        mViewPager.setCurrentItem(0);

        mTabs.post(new Runnable() {
            @Override
            public void run() {
                TabLayoutUtil.setIndicator(mTabs, 55, 55);
            }
        });
        mTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
              //  Toast.makeText(mContext, "选中的"+tab.getText(), Toast.LENGTH_SHORT).show();
            //    ToastUtils.makeToastShort("选中的");
                mModel.getData(1,20,GroupActivity.this);
                //通过广播设置,点击后立即刷新
                Intent intent = new Intent();
                intent.setAction("Refresh2");
                sendOrderedBroadcast(intent, null);   //有序广播发送

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
              //  Toast.makeText(mContext, "未选中的"+tab.getText(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
             //   Toast.makeText(mContext, "复选的"+tab.getText(), Toast.LENGTH_SHORT).show();
            //    ToastUtils.makeToastShort("复选中的");
                mModel.getData(1,20,GroupActivity.this);
            }
        });
    }
    private void initView() {
        /*mTbGrouping = (TitleBar)findViewById(R.id.tb_grouping);
        mTbGrouping.setTitle("拼团");*/
        mImageView = (ImageView) findViewById(R.id.iv_back_g);
        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mBanner = (FlyBanner)findViewById(R.id.banner);
        mTabs = (TabLayout)findViewById(R.id.tabs);
        mViewPager = (NoScrollViewPager)findViewById(R.id.vp_fragment_grouping);
        mAppBarLayout = (AppBarLayout)findViewById(R.id.appBarLayout);
        mVpSwipeRefesh = (VpSwipeRefreshLayout)findViewById(R.id.vpSwipeRefreshLayout);
        mVpSwipeRefesh.setOnRefreshListener(this) ;

        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset >= 0) {
                    mVpSwipeRefesh.setEnabled(true);
                } else {
                    mVpSwipeRefesh.setEnabled(false);
                }
            }
        });
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int width = dm.widthPixels;
        int height = width * 380 / 800;
        //  int height = width*216/319;
        LinearLayout.LayoutParams params = new AppBarLayout.LayoutParams(width, height);
        //获取当前控件的布局对象
        //params.height=width;//设置当前控件布局的高度
        mBanner.setLayoutParams(params);//将设置好的布局参数应用到控件中
        mTitle.add("团购精选");
        mTitle.add("我的拼团");
       /* MyGroupingFragments fragments0 = */

        mFragment.add(new GroupingSelectFragment());
        mFragment.add(new MyGroupingFragments().newInstance("0"));

    }
        @Subscribe(threadMode = ThreadMode.MAIN)

    public void onMessageEvent(MessageEvent event) {
        LogUtils.e("event", event.message);//E/event: GroupOrderDetailsActivity
        if (!event.message.isEmpty()) {
            //如果广播信息不为空,那就默认选择中第一个
            mViewPager.setCurrentItem(0);
        }
    }

    @Override
    public void ongetGroupingDataSuccess(Object object) {
        if (mVpSwipeRefesh.isRefreshing()) {
            mVpSwipeRefesh.setRefreshing(false);
        }
        mDatabean = (GroupingIndexBean) object;
        mGroupsadv = mDatabean.getGroupsadv();
        if (page==1) {
            networkImages.clear();
        }else {
            if (mGroupsadv.size()==0) {
                return;
            }
        }
        if (mGroupsadv != null ) {
            for (int i = 0; i < mGroupsadv.size(); i++) {
                networkImages.add(mGroupsadv.get(i).getThumb());
            }
        }
        //轮播图加载网络图片
        initNetBanner();

    }

    private void initNetBanner() {
        if (networkImages.size() > 0) {
            mBanner.setImagesUrl(networkImages);
        }

        mBanner.setOnItemClickListener(new FlyBanner.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (mGroupsadv != null) {
               /*     if (ASUtils.isCanUse(mGroupsadv.get(position).getLink())) {*/
                    if (ASUtils.isCanUse(mGroupsadv.get(position).getLinktype())) {
                        if ("2".equals(mGroupsadv.get(position).getLinktype())) {
                            Intent intent = new Intent(GroupActivity.this, GroupingDetailsActivity.class);
                            intent.putExtra("id", mGroupsadv.get(position).getLink());
                            startActivity(intent);
                        } else /*if ("1".equals(mGroupsadv.get(position).getLinktype()))*/ {
                            Intent intent = new Intent(GroupActivity.this, WebViewActivity.class);
                            intent.putExtra("data", mGroupsadv.get(position).getLink());
                            startActivity(intent);
                        }
                      /*  }*/
                    }
                }

            }
        });
    }

    @Override
    public void ongetGroupingDataError(Object object) {
        if (mVpSwipeRefesh.isRefreshing()) {
            mVpSwipeRefesh.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
   //     NoTokenUtils.loginOut(GroupActivity.this, jsonObject);
   //     ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }

    @Override
    public void onRefresh() {
        mModel.getData(1,20,GroupActivity.this);
        // 显示充值成功的页面和需要的操作
        Intent intent = new Intent();
        intent.setAction("Refresh");
        sendOrderedBroadcast(intent, null);   //有序广播发送
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
